package cn.yili12.server.client.handler;

import cn.yili12.common.util.JwtUtil;
import cn.yili12.server.client.vo.ClientMessage;
import cn.yili12.server.info.vo.InfoMessage;
import cn.yili12.server.info.vo.InfoMessageType;
import cn.yili12.server.websocket.NioWebSocketChannelPool;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@Slf4j
public class LoginClientHandler extends BaseClientHandler {

    @Autowired
    private NioWebSocketChannelPool webSocketChannelPool;


    @Override
    public void handler(ClientMessage message) {
        String token = message.getData();
        String user = JwtUtil.getUser(token);
        String org = JwtUtil.getOrg(token);
        //1.保存用户对应的通道
        if (StringUtils.isEmpty(user) || StringUtils.isEmpty(org)) {
            log.warn("token错误，没有找到用户名或者密码");
            this.channel.close();
            return;
        }
        webSocketChannelPool.add(org, user, channel);
        log.info("用户{}绑定连接成功，key={}", new Object[]{user, channel.id().asLongText()});
        //转对象
        InfoMessage infoMessage = toInfoMessage(message.getData(), message.getFrom(), message.getTo(), message.getNo(), InfoMessageType.Online);
        //2.通知所有用戶我上线了
        producer.send(properties.getInfoQueue(), JSON.toJSONString(infoMessage));
        //3.通知业务系统我上线了
        producer.send(properties.getDbQueue(), JSON.toJSONString(infoMessage));
    }

}
